package com.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
 *
 * 功能描述: WorkStealingPool是一个基于工作窃取算法的线程池，用于提高多核CPU的利用率。
 *
 * @param:
 * @return: 
 * @auther: csh
 * @date: 2023/3/6 11:18 下午
 */
public class WorkStealingPoolStudy {
    public static void main(String[] args) {
        // 获取当前系统的CPU核心数
        int processors = Runtime.getRuntime().availableProcessors();
        // 创建一个基于工作窃取算法的线程池
        ExecutorService executorService = Executors.newWorkStealingPool(processors);
        // 提交10个任务
        for (int i = 1; i <= 1000; i++) {
            executorService.execute(new Task(i));
        }
        // 等待所有任务执行完毕
        try {
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 关闭线程池
        executorService.shutdown();
    }
    static class Task implements Runnable {
        private int taskId;
        public Task(int taskId) {
            this.taskId = taskId;
        }
        @Override
        public void run() {
            System.out.println("任务" + taskId + "开始执行，当前线程名为" + Thread.currentThread().getName());
            try {
                // 模拟任务执行的耗时
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务" + taskId + "执行完毕，当前线程名为" + Thread.currentThread().getName());
        }
    }
}